<?php

namespace app\api\controller;

use app\admin\model\Memberresume;
use app\lib\exception\ParameterException;
use app\common\validate\UserSubmitExamine;
use app\common\BaseHelper;

use app\admin\model\Townprogram;
use app\admin\model\Area;
use app\admin\model\Member;
use app\admin\model\Memberextrainfo;
use app\admin\model\Povertymember;
use app\admin\service\Member as MemberService;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 身份认证
 */
class UserAuth extends BaseController
{

    /**
     * 首页
     */
    public function getHomeFrame(){
        $param = self::getHttpParam();

        /*if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }*/
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }

        $userId = $param->userId;
        $where = [
            'userId' => $userId
        ];

        $member = Member::where($where)->find();
        $checkParty = $checkInstitution = $checkVillager = $checkPoverty = '';
        if($member){
            $checkParty = $member['checkParty'];
            $checkInstitution = $member['checkInstitution'];
            $checkVillager = $member['checkVillager'];
            $checkPoverty = $member['checkPoverty'];
        }

        $data = [
            'checkParty' => $checkParty ? : '',
            'checkInstitution' => $checkInstitution ? : '',
            'checkVillager' => $checkVillager ? : '',
            'checkPoverty' => $checkPoverty ? : '',
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 保存基础信息
     */
    public function saveBaseinfo(){
        (new UserSubmitExamine())->goCheck();

        $param = self::getHttpParam();

        /*try {
            $this->checkParams($param);
        } catch (Exception $e) {
            return show(config('status.ERROR_STATUS'), $e->msg, $e->msg);
        }*/

        $userId = $param->userId;
        $townId = $param->townId;

        try {
            $Townprogram = Townprogram::where('townId',$townId)->find();
            if(!$Townprogram){
                throw new ParameterException([
                    'msg' => '镇不存在'
                ]);
            }
            // TODO 已删除的怎么处理
            $Member = Member::where(['identityNumber' => $param->identityNumber])->find();
            if ($Member) {
                if($Member->isDelete == 2 && $Member->memberType == 1 && ($Member->townId != $townId || $Member->cityId != $Townprogram->cityId || $Member->xianId != $Townprogram->xianId)){
                    throw new ParameterException([
                        'msg' => '您已经是其它镇/村的人了！'
                    ]);
                }

                $Member->name = $param->name;
                $Member->userId = $userId;
                $Member->townId = $townId;
                $Member->cityId = $Townprogram->cityId;
                $Member->xianId = $Townprogram->xianId;
                $Member->villageId = !empty($param->villageId) ? $param->villageId : 0;
                $Member->identityNumber = $param->identityNumber;
                //$genderNum = substr($Member->identityNumber,-2,1);
                //$Member->gender = ((int)$genderNum)%2 == 0 ? 2 : 1;
                $Member->gender = $param->gender;
                $birthday = substr($Member->identityNumber,6,4).'-'.substr($Member->identityNumber,10,2).'-'.substr($Member->identityNumber,12,2);
                $Member->birthday = $birthday;
                //$Member->cardImg = $param->cardImg;
                if(isset($param->avatar)){
                    $Member->avatar = $param->avatar;
                }
                if(!$Member->mobile && isset($param->mobile) && !empty($param->mobile)){
                    $Member->mobile = $param->mobile;
                }
                if(isset($param->homeImg)){
                    $Member->homeImg = $param->homeImg;
                }
                $Member->ethnicId = $param->ethnicId;
                $Member->religiousFaith = $param->religiousFaith;
                $Member->education = $param->education;
                $Member->memberType = $param->memberType;
                $Member->address = $param->address;
                $Member->isDelete = 2;

                $result = $Member->save();
                if($result === false){
                    throw new ParameterException([
                        'msg' => '保存失败'
                    ]);
                }
            } else {
                $Member = new Member();
                $Member->id = BaseHelper::getUUID();
                $Member->name = $param->name;
                $Member->userId = $userId;
                $Member->townId = $townId;
                $Member->cityId = $Townprogram->cityId;
                $Member->xianId = $Townprogram->xianId;
                $Member->villageId = !empty($param->villageId) ? $param->villageId : 0;
                $Member->identityNumber = $param->identityNumber;
                //$genderNum = substr($Member->identityNumber,-2,1);
                //$Member->gender = ((int)$genderNum)%2 == 0 ? 2 : 1;
                $Member->gender = $param->gender;
                $birthday = substr($Member->identityNumber,6,4).'-'.substr($Member->identityNumber,10,2).'-'.substr($Member->identityNumber,12,2);
                $Member->birthday = $birthday;
                //$Member->cardImg = $param->cardImg;
                if(isset($param->avatar)){
                    $Member->avatar = $param->avatar;
                }
                if(isset($param->mobile) && !empty($param->mobile)){
                    $Member->mobile = $param->mobile;
                }
                if(isset($param->homeImg)){
                    $Member->homeImg = $param->homeImg;
                }
                $Member->ethnicId = $param->ethnicId;
                $Member->religiousFaith = $param->religiousFaith;
                $Member->education = $param->education;
                $Member->memberType = $param->memberType;
                $Member->address = $param->address;
                $Member->isDelete = 2;

                $result = $Member->save();
                if($result === false){
                    throw new ParameterException([
                        'msg' => '添加失败'
                    ]);
                }
            }

            $member = Member::get($Member->id);
            $member = $this->getMemberInfo($member);

            return show(config('status.SUCCESS_STATUS'), '保存成功', $member);
        } catch (Exception $e){
            return show(config('status.ERROR_STATUS'),isset($e->msg)?$e->msg:$e->getMessage(),isset($e->msg)?$e->msg:$e->getMessage());
        }
    }

    /**
     * 党员认证
     */
    public function authParty(){
        $param = self::getHttpParam();

        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'memberId 不能为空');
        }
        if (empty($param->partyTime)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '入党时间(partyTime) 不能为空');
        }
        if (empty($param->organizationId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '党组织(organizationId) 不能为空');
        }
        if (empty($param->job)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '党职务(job) 不能为空');
        }

        $memberId = $param->memberId;
        try {
            $model = new Member();
            $data = [
                'checkParty' => 2,
                'isParty' => 1,
                'organizationId' => $param->organizationId,
                'partyTime' => strtotime($param->partyTime),
                'job' => $param->job
            ];

            $result = $model->allowField(true)->save($data, ['id' => $memberId]);

            if($result !== false){
                $member = Member::get($memberId);
                $member = $this->getMemberInfo($member);

                return show(config('status.SUCCESS_STATUS'),'认证成功', $member);
            }else{
                return show(config('status.ERROR_STATUS'),'认证失败', []);
            }
        } catch (Exception $e) {
            return show(config('status.ERROR_STATUS'), $e->getMessage(), $e->getMessage());
        }
    }

    /**
     * 公职人员认证
     */
    public function authInstitution(){
        $param = self::getHttpParam();

        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'memberId 不能为空');
        }
        if (empty($param->institutionId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '机关(institutionId) 不能为空');
        }
        if (empty($param->departmentId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '部门(departmentId) 不能为空');
        }
        if (empty($param->institutionJob)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '机关职务(institutionJob) 不能为空');
        }
        if (empty($param->workDuty)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '工作工作职责(workDuty) 不能为空');
        }
        /*if (empty($param->startTime)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '工作开始时间(startTime) 不能为空');
        }
        if (empty($param->endTime)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '结束时间(endTime) 不能为空');
        }
        if (empty($param->resume)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '工作履历(resume) 不能为空');
        }*/

        $memberId = $param->memberId;
        Db::startTrans();
        try {
            $model = new Member();
            $data = [
                'checkInstitution' => 2,
                'institutionId' => $param->institutionId,
                'departmentId' => $param->departmentId,
                'institutionJob' => $param->institutionJob
            ];

            $result = $model->allowField(true)->save($data, ['id' => $memberId]);

            if($result !== false){
                $startTime = [];
                $endTime = [];
                $resume = [];
                if(!empty($param->resumeList)){
                    $resumeList = $param->resumeList;
                    foreach ($resumeList as $value) {
                        $startTime[] = $value->startTime;
                        $endTime[] = $value->endTime;
                        $resume[] = $value->resume;
                    }
                }

                $extraData = [
                    'id' => $memberId,
                    'workDuty' => $param->workDuty,
                    'startTime' => $startTime,
                    'endTime' => $endTime,
                    'resume' => $resume,
                ];
                $res = MemberService::saveExtrainfo($extraData);
                if($res['code'] != 1){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'),'保存额外信息失败', []);
                }

                Db::commit();
                $member = Member::get($memberId);
                $member = $this->getMemberInfo($member);

                return show(config('status.SUCCESS_STATUS'),'认证成功', $member);
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'),'认证失败', []);
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), $e->getMessage(), $e->getMessage());
        }
    }

    /**
     * 村居民认证
     */
    public function authVillager(){
        $param = self::getHttpParam();

        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'memberId 不能为空');
        }
        if (empty($param->health)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '健康状况(health) 不能为空');
        }
        if (empty($param->laborSkills)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '劳动技能(laborSkills) 不能为空');
        }
        if (empty($param->perIncome)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '人均纯收入(perIncome) 不能为空');
        }
        if (empty($param->workStatus)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '务工情况(workStatus) 不能为空');
        }
        if (empty($param->workTime)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '务工时间(workTime) 不能为空');
        }
        if (empty($param->specialGroup) && $param->specialGroup != 0) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '特殊群体(specialGroup) 不能为空');
        }
        /*if (empty($param->villageJob)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '村职务(villageJob) 不能为空');
        }*/
        if (empty($param->isHouseholder)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '是否户主(isHouseholder) 不能为空');
        } else {
            if($param->isHouseholder != 1){
                if (empty($param->householderId)) {
                    return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '户主(householderId) 不能为空');
                }
                if (empty($param->relatedHouseholder)) {
                    return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '与户主关系(relatedHouseholder) 不能为空');
                }
            }
        }

        $memberId = $param->memberId;
        Db::startTrans();
        try {
            $model = new Member();
            $data = [
                'checkVillager' => 2,
                'health' => $param->health,
                //'villageJob' => $param->villageJob,
            ];
            if(!empty($param->villageJob)){
                $data['villageJob'] = $param->villageJob;
            }

            $result = $model->allowField(true)->save($data, ['id' => $memberId]);

            if($result !== false){
                $extraData = [
                    'id' => $memberId,
                    'laborSkills' => $param->laborSkills,
                    'perIncome' => $param->perIncome / 100,
                    'workStatus' => $param->workStatus,
                    'workTime' => $param->workTime,
                    'specialGroup' => $param->specialGroup,
                    'isHouseholder' => $param->isHouseholder,
                    'householderId' => isset($param->householderId) ? $param->householderId : '',
                    'relatedHouseholder' => isset($param->relatedHouseholder) ? $param->relatedHouseholder : '',
                    'onlyVillager' => true
                ];
                $res = MemberService::saveExtrainfo($extraData);
                if($res['code'] != 1){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'),'保存额外信息失败', []);
                }

                Db::commit();
                $member = Member::get($memberId);
                $member = $this->getMemberInfo($member);

                return show(config('status.SUCCESS_STATUS'),'认证成功', $member);
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'),'认证失败', []);
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), $e->getMessage(), $e->getMessage());
        }
    }

    /**
     * 贫困户认证
     */
    public function authPoverty(){
        $param = self::getHttpParam();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId 不能为空');
        }
        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'memberId 不能为空');
        }
        if (empty($param->povertydegree)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '贫困户属性(povertydegree) 不能为空');
        }
        if (empty($param->povertyreason)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '致贫原因(povertyreason) 不能为空');
        }
        if (empty($param->outpoverty)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '脱贫属性(outpoverty) 不能为空');
        }
        /*if (empty($param->outPovertyYear)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '脱贫年度(outPovertyYear) 不能为空');
        }*/
        if (empty($param->isDangerHouse)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '是否危房户(isDangerHouse) 不能为空');
        }
        if (empty($param->isSeriousIllness)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '参加大病医疗(isSeriousIllness) 不能为空');
        }
        if (empty($param->aidingId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '帮扶人(aidingId) 不能为空');
        }

        $memberId = $param->memberId;
        Db::startTrans();
        try {
            $model = new Member();
            $data = [
                'checkPoverty' => 2,
                'isPoverty' => 1,
            ];

            $result = $model->allowField(true)->save($data, ['id' => $memberId]);

            if($result !== false){
                $xianId = Area::where('id', $param->townId)->value('parentId');
                $cityId = Area::where('id', $xianId)->value('parentId');

                $povertymember = Povertymember::where('memberId', $memberId)->find();
                if ($povertymember) {
                    $povertymember->cityId = $cityId;
                    $povertymember->xianId = $xianId;
                    $povertymember->townId = $param->townId;
                    $povertymember->villageId = $param->villageId;
                    $povertymember->updateDate = time();
                    $povertymember->povertydegree = $param->povertydegree;
                    $povertymember->povertyreason = $param->povertyreason;
                    $povertymember->outpoverty = $param->outpoverty;
                    $povertymember->outPovertyYear = isset($param->outPovertyYear) ? $param->outPovertyYear : '';
                    $povertymember->isDangerHouse = $param->isDangerHouse;
                    $povertymember->isSeriousIllness = $param->isSeriousIllness;
                    $povertymember->aidingId = $param->aidingId;

                    $res = $povertymember->save();
                } else {
                    $poverty = [
                        'id' => BaseHelper::getUUID(),
                        'cityId' => $cityId,
                        'xianId' => $xianId,
                        'townId' => $param->townId,
                        'villageId' => $param->villageId,
                        'createDate' => time(),
                        'memberId' => $memberId,
                        'povertydegree' => $param->povertydegree,
                        'povertyreason' => $param->povertyreason,
                        'outpoverty' => $param->outpoverty,
                        'outPovertyYear' => isset($param->outPovertyYear) ? $param->outPovertyYear : '',
                        'isDangerHouse' => $param->isDangerHouse,
                        'isSeriousIllness' => $param->isSeriousIllness,
                        'aidingId' => $param->aidingId,
                    ];
                    $res = Povertymember::insert($poverty);
                }
                if($res === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'),'保存贫困户信息失败', []);
                }

                Db::commit();
                $member = Member::get($memberId);
                $member = $this->getMemberInfo($member);

                return show(config('status.SUCCESS_STATUS'),'认证成功', $member);
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'),'认证失败', []);
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), $e->getMessage(), $e->getMessage());
        }
    }

    /**
     * 删除工作履历
     */
    public function delResume(){
        $param = self::getHttpParam();

        /*if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'memberId 不能为空');
        }*/
        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '工作履历ID(id) 不能为空');
        }

        $where = [
            'id' => $param->id
        ];
        $model = new Memberresume();
        $result = $model->where($where)->delete();

        if($result !== false){
            return show(config('status.SUCCESS_STATUS'),'删除成功', []);
        }else{
            return show(config('status.ERROR_STATUS'),'删除失败', []);
        }
    }

    // 检查基本信息
    protected function checkParams($param){
        if (empty($param->gender)) {
            throw new ParameterException([
                'msg' => '性别(gender)不能为空'
            ]);
        }
        if (empty($param->mobile)) {
            throw new ParameterException([
                'msg' => '手机号(mobile)不能为空'
            ]);
        }
        if (empty($param->ethnicId)) {
            throw new ParameterException([
                'msg' => '名族(ethnicId)不能为空'
            ]);
        }
        if (empty($param->religiousFaith)) {
            throw new ParameterException([
                'msg' => '宗教信仰(religiousFaith)不能为空'
            ]);
        }
        if (empty($param->education)) {
            throw new ParameterException([
                'msg' => '文化程度(education)不能为空'
            ]);
        }
        if (empty($param->memberType)) {
            throw new ParameterException([
                'msg' => '类型(memberType)不能为空'
            ]);
        } else {
            if ($param->memberType == 1) {
                if (empty($param->villageId)) {
                    throw new ParameterException([
                        'msg' => '所属村(villageId)不能为空'
                    ]);
                }
            }
        }
        if (empty($param->address)) {
            throw new ParameterException([
                'msg' => '所在地(address)不能为空'
            ]);
        }
    }
}